using DG.Tweening;
using UnityEngine;

public class RectMesh : MeshBase
{
    public float m_Width;
    public float m_Length;
    
    public PivotAlign m_WidthAlign = PivotAlign.Center;
    public PivotAlign m_LengthAlign = PivotAlign.Center;

    protected override void InitMesh()
    {
        if (mMeshFilter == null) Init();

        mTriangles = new int[] {0, 2, 3, 0, 3, 1};
        mUVs = new Vector2[4];
        mUVs[0].x = 0;
        mUVs[0].x = 0;

        mUVs[1].x = 1;
        mUVs[1].y = 0;

        mUVs[2].x = 0;
        mUVs[2].y = 1;

        mUVs[3].x = 1;
        mUVs[3].y = 1;
        UpdateShape();
    }

    protected override void UpdateShape()
    {
        float w2 = m_Width*0.5f;
        float l2 = m_Length*0.5f;

        mVector3s = new Vector3[4];
        float x0, z0, x1, z1, x2, z2, x3, z3;
        x0 = z0 = x1 = z1 = x2 = z2 = x3 = z3 = 0;

        switch (m_WidthAlign)
        {
            case PivotAlign.Left:
                x0 = 0f;
                x1 = m_Width;
                x2 = 0;
                x3 = m_Width;
                break;
            case PivotAlign.Center:
                x0 = -w2;
                x1 = w2;
                x2 = -w2;
                x3 = w2;
                break;
            case PivotAlign.Right:
                x0 = -m_Width;
                x1 = 0f;
                x2 = -m_Width;
                x3 = 0f;
                break;          
        }
        switch (m_LengthAlign)
        {
            case PivotAlign.Left:
                z0 = 0;
                z1 = 0;
                z2 = m_Length;
                z3 = m_Length;
                break;
            case PivotAlign.Center:
                z0 = -l2;
                z1 = -l2;
                z2 = l2;
                z3 = l2;
                break;
            case PivotAlign.Right:
                z0 = -m_Length;
                z1 = -m_Length;
                z2 = 0f;
                z3 = 0f;
                break;         
        }

        mVector3s[0].x = x0;
        mVector3s[0].y = 0;
        mVector3s[0].z = z0;

        mVector3s[1].x = x1;
        mVector3s[1].y = 0;
        mVector3s[1].z = z1;

        mVector3s[2].x = x2;
        mVector3s[2].y = 0;
        mVector3s[2].z = z2;

        mVector3s[3].x = x3;
        mVector3s[3].y = 0;
        mVector3s[3].z = z3;
        UpdateMesh();
    }

    public float Length
    {
        get => m_Length;
        set
        {
            m_Length = value;
            UpdateShape();
        }
    }

    public override Tweener DoAnim(float endValue, float duration, float delay)
    {
        return DOTween.To(() => Length, x => Length = x, endValue, duration).SetDelay(delay);
    }
    
}
